﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using NetBay.Core.BusinessEntities;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.Context;
using Telerik.Windows.Controls;
using WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation;

#endregion

namespace Rio.Framework.Pages.ChildWindows
{
    public partial class CreateAlertWindow
    {
        #region Readonly & Static Fields

        private readonly List<Folder> m_oFolderList;

        #endregion

        #region Fields

        private List<Group> m_oSelectedGroupList;
        private string m_sLabelFolderIndexes;

        #endregion

        #region Constructors

        /// <summary>
        ///   Initializes a new instance of the <see cref="CreateAlertWindow" /> class.
        /// </summary>
        public CreateAlertWindow()
        {
            InitializeComponent();
            InitLabel();
            AlertDateTime.SelectableDateStart = DateTime.Today.AddDays(1);

            CanMove = true;
            ResizeMode = ResizeMode.NoResize;
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
        }

        /// <summary>
        ///   Initializes a new instance of the <see cref="CreateAlertWindow" /> class.
        /// </summary>
        /// <param name="p_oListFolder"> The p_o list folder. </param>
        public CreateAlertWindow(List<Folder> p_oListFolder)
            : this()
        {
            m_oFolderList = p_oListFolder;
            int l_oFolderCpt = 1;
            foreach (Folder l_oForder in m_oFolderList)
            {
                if (m_oFolderList.Count > 1)
                {
                    MemoTextBox.Text += "\n\n- " + m_sLabelFolderIndexes + ": " + l_oFolderCpt + " ----------------- \n";
                }
                else
                {
                    MemoTextBox.Text += "\n\n- " + m_sLabelFolderIndexes + " ----------------- \n";
                }

                int i = 0;
                foreach (Index l_oIndex in l_oForder.ListIndex)
                {
                    string l_sIndexValue = l_oForder.ListValues.ElementAt(i);
                    if (!string.IsNullOrEmpty(l_sIndexValue) && l_oIndex.Type == (int) IndexDomainServiceEnums.IndexType.ListOfValues)
                    {
                        l_sIndexValue = l_sIndexValue.Split(';')[0];
                    }

                    if (!string.IsNullOrEmpty(l_sIndexValue))
                    {
                        MemoTextBox.Text += l_oIndex.IndexLabel + " : " + l_sIndexValue + "\n";
                    }
                    i++;
                }

                l_oFolderCpt++;
            }
        }

        #endregion

        #region Instance Methods

        /// <summary>
        ///   Inits the label.
        /// </summary>
        private void InitLabel()
        {
            buttonSend.Content = Resx.GetLabel(ResxAlert.ALERT_CREATE);
            buttonCancel.Content = Resx.GetLabel(ResxAlert.CANCEL);
            LabelAlertName.Content = string.Format("{0}", Resx.GetLabel(ResxAlert.ALERT_NAME));
            LabelAlertDateTime.Content = string.Format("{0}", Resx.GetLabel(ResxAlert.ALERT_DATE));
            LabelAlertObject.Content = string.Format("{0}", Resx.GetLabel(ResxAlert.ALERT_OBJECT));
            LabelAlertBody.Content = string.Format("{0}", Resx.GetLabel(ResxAlert.ALERT_BODY));
            Header = Resx.GetLabel(ResxCommon.ALERT);
            ButtonTo.Content = Resx.GetLabel(ResxAlert.SEND_TO);
            ValidatorMsg.Text = Resx.GetLabel(ResxAlert.VALIDATE_MSG);
            m_sLabelFolderIndexes = Resx.GetLabel(ResxAlert.FOLDER_INDEX_LABEL);
        }

        /// <summary>
        ///   Validates the fields.
        /// </summary>
        /// <returns> </returns>
        private bool ValidateFields()
        {
            bool l_bValidationResult = true;
            if (string.IsNullOrEmpty(AlertName.Text))
            {
                l_bValidationResult = false;
            }

            if (string.IsNullOrEmpty(ToTextBox.Text))
            {
                l_bValidationResult = false;
            }

            if (string.IsNullOrEmpty(ObjectTextBox.Text))
            {
                l_bValidationResult = false;
            }

            if (AlertDateTime.SelectedDate == null)
            {
                l_bValidationResult = false;
            }
            else
            {
                if (AlertDateTime.SelectedDate < DateTime.Now)
                {
                    l_bValidationResult = false;
                }
            }

            return l_bValidationResult;
        }

        #endregion

        #region Event Handling

        /// <summary>
        ///   Group filter window event closing
        /// </summary>
        /// <param name="sender"> </param>
        /// <param name="e"> </param>
        private void L_oGroupFilterWindow_Closed(object sender, EventArgs e)
        {
            GroupFilterWindow L_oGroupFilterWindow = (GroupFilterWindow) sender;

            //if a value has been selected
            if (L_oGroupFilterWindow.DialogResult == true)
            {
                try
                {
                    m_oSelectedGroupList = L_oGroupFilterWindow.m_szSelectedItems;
                    ToTextBox.Text = L_oGroupFilterWindow.InputValue;
                }
                catch (Exception)
                {
                    //Logger.Write("CANNOT GET SELECTED GROUP : " + Environment.NewLine + ex, Logger.Level.Error);
                }
            }
        }

        /// <summary>
        ///   Handles the Click event of the buttonCancel control.
        /// </summary>
        /// <param name="sender"> The source of the event. </param>
        /// <param name="e"> The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data. </param>
        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        ///   Event raised on button send click
        /// </summary>
        /// <param name="sender"> </param>
        /// <param name="e"> </param>
        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            if (ValidateFields())
            {
                List<long> l_oGroupId = m_oSelectedGroupList.Select(l_oGroup => l_oGroup.Identifier).ToList();
                Dictionary<long, long> l_oFolders = m_oFolderList.ToDictionary(l_oFolder => l_oFolder.Identifier, l_oFolder => l_oFolder.FolderTypeIdentifier);

                //Get the action id, it can be null
                int? actionId = null;
                if(chkDeleteFolder.IsChecked.Value)
                {
                    actionId = 1;
                }

                GlobalWebContext.BusinessEntitiesDomainContext.AddAlert(AlertName.Text, ObjectTextBox.Text, MemoTextBox.Text, AlertDateTime.SelectedDate.Value, l_oFolders, l_oGroupId, actionId,
                                                                        delegate(InvokeOperation<IEnumerable<ReturnLong>> retr)
                                                                            {
                                                                                if (retr != null && retr.Value != null)
                                                                                {
                                                                                    ReturnLong l_oRet = retr.Value.First();
                                                                                    DialogResult = l_oRet.IsValid;
                                                                                    Close();
                                                                                }
                                                                            }, null);
            }
            else
            {
                ValidatorMsg.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        ///   Handles the Click event of the buttonTo control.
        /// </summary>
        /// <param name="sender"> The source of the event. </param>
        /// <param name="e"> The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data. </param>
        private void buttonTo_Click(object sender, RoutedEventArgs e)
        {
            GroupFilterWindow l_oGroupFilterWindow = new GroupFilterWindow(ToTextBox.Text);
            l_oGroupFilterWindow.Closed += L_oGroupFilterWindow_Closed;
            l_oGroupFilterWindow.ShowDialog();
        }

        #endregion
    }
}